﻿using CSRedis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Newtonsoft.Json;
using QskjDownUpAlarmVideoImage.Dto;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace QskjDownUpAlarmVideoImage.Service
{
    public class DownUpVideoImage
    {
        public static CSRedisClient? cSRedisClient { get; set; }
        /// <summary>
        /// 上传视图库数据结构
        /// </summary> 
        /// <param name="key">Id</param>
        /// <param name="s">格式</param>
        /// <param name="n">文件名</param>
        /// <returns></returns>
        public static async Task<string> PostFileDataInfo(string key, string s, string n, string bt)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/VideoSlices");
            var content = new StringContent("{\r\n    \"VideoSliceListObject\": {\r\n        \"VideoSlice\": [\r\n            {\r\n                \"VideoSliceInfo\": {\r\n                    \"VideoID\": \"" + key + "\",\r\n                    \"InfoKind\": 0,\r\n                    \"VideoSource\": \"\",\r\n                    \"FileFormat\": \"" + s + "\",\r\n                    \"CodedFormat\": \"\",\r\n                    \"AudioFlag\": 0,\r\n                    \"Title\": \"" + n + "\",\r\n                    \"ContentDescription\": \"\",\r\n                    \"ShotPlaceCode\": \"\",\r\n                    \"VideoLen\": 0.0,\r\n                    \"BeginTime\": \"" + bt + "\",\r\n                    \"EndTime\": \"\",\r\n                    \"TimeErr\": 0,\r\n                    \"Width\": 0,\r\n                    \"Height\": 0\r\n                }\r\n            }\r\n        ]\r\n    }\r\n}", null, "application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 上传视图库视频文件
        /// </summary>
        /// <returns></returns>
        public static async Task<string> PostFileData(string key, string filePath = null)
        {
            using (FileStream file = File.OpenRead(filePath))
            {
                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/FileData/" + key + "/VideoSlices");
                //request.Content = (content);
                //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                request.Content = new StreamContent(file);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                string res = await response.Content.ReadAsStringAsync();
                return res;
            }
        }
        /// <summary>
        /// 视图库视频文件查询
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetFileDataUrl(string key, string begintime)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, $@"http://192.168.3.223:8000/VIID/VideoSlices?VideoID={key}&BeginTime={begintime}");
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 上传视图库图片文件
        /// </summary>
        /// <param name="key">Id</param>
        /// <param name="s">格式</param>
        /// <param name="n">文件名</param>
        /// <param name="data">文件base64</param>
        /// <returns></returns>
        public static async Task<string> PostImageFileData(string key, string s, string n, string data)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/Images?ResultObj=1");
            var content = new StringContent("{\r\n    \"ImageListObject\": {\r\n        \"Image\": [\r\n            {\r\n                \"ImageInfo\": {\r\n                    \"ImageID\": \"" + key + "\",\r\n                    \"InfoKind\": 2,\r\n                    \"ImageSource\": \"19\",\r\n                    \"Title\": \"" + n + "\",\r\n                    \"ContentDescription\": \"picture\",\r\n                    \"ShotPlaceFullAdress\": \"1\",\r\n                    \"SecurityLevel\": \"5\",\r\n                    \"ShotTime\": \"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",\r\n                    \"Height\": 0,\r\n                    \"FileFormat\": \"" + s + "\",\r\n                    \"Width\": 0\r\n                },\r\n                \"Data\": \"" + data + "\"\r\n            }\r\n        ]\r\n    }\r\n}", null, "application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 视图库图片文件查询
        /// </summary>
        /// <param name="key">Id</param>
        /// <returns></returns>
        public static async Task<string> GetImageFileDataUrl(string key)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://192.168.3.223:8000/VIID/Images?ImageID=" + key);
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        public static void GetInfo(int day = 0)
        {
            try
            {
                string dtStr = DateTime.Now.AddDays(day).ToString("yyyyMMdd");
                if (DateTime.Now.Hour < 3)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_FileResourceInfo{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sqlCt = $@"create table IF NOT EXISTS qskjrecord.B_FileResourceInfo{dtStr}
                                (
                                   id                   bigint not null auto_increment,
                                   typeinfo             bigint comment '类型信息，1-稽查，2-录像下载，3-报警',
                                   alarmId              varchar(300) comment '报警Id',
                                   platform             varchar(50) comment '文件来源平台',
                                   filetype             varchar(50) comment '文件类型',
                                   filekey              varchar(50) comment '视图库key值',
                                   company              varchar(50) comment '公司',
                                   filiale              varchar(50) comment '车队',
                                   license              varchar(50) comment '车牌',
                                   driver               varchar(50) comment '驾驶员',
                                   ipaddress            varchar(50) comment 'IP地址',
                                   urladdress           text comment '文件地址',
                                   createtime           datetime comment '创建时间',
                                   updatetime           datetime comment '更新时间',
                                   pid                  bigint comment '关联表数据Id',
                                   begintime            varchar(50) comment '开始时间',
                                   endtime              varchar(50) comment '结束时间',
                                   primary key (id)
                                );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlCt);
                    }
                }
                string sql = $@"select a.* from qskjrecord.B_Vehicle_AlarmAndFile{dtStr} a
                                left join qskjrecord.B_FileResourceInfo{dtStr} b on a.id=b.pid
                                join qskj.R_Alarm_Type c on a.alarmtype=typeId
                                where (((a.platform='RUIMING' or a.platform='zl') and c.busOrCar='c')or (a.platform='ZAKJ' and c.busOrCar='b')) and c.threeClassId=1 and LENGTH(a.url)>0 and  b.id is null AND (url NOT REGEXP '.no' and url NOT REGEXP '.bin')  order by a.id limit 3;";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    string x = dr["url"].ToString().Replace("61.171.114.101", "192.168.3.231");
                    string[] strUrl = x.Split(';');
                    //Console.WriteLine(x);
                    foreach (string strUrl2 in strUrl)
                    {
                        if (string.IsNullOrWhiteSpace(strUrl2) || strUrl2.Contains(".no") || strUrl2.Contains(".bin"))
                        {
                            continue;
                        }
                        // ThreadPoll启动多线程
                        ThreadPool.QueueUserWorkItem(p => UploadFileVideo(strUrl2, dr["alarmId"].ToString(), dr["platform"].ToString(), Convert.ToString(dr["alarmtype"] == DBNull.Value ? "" : dr["alarmtype"]), Convert.ToInt32(dr["id"] == DBNull.Value ? 0 : dr["id"]), dtStr));
                        //UploadFileVideo(strUrl2, dr["alarmId"].ToString(), dr["platform"].ToString(), Convert.ToString(dr["alarmtype"] == DBNull.Value ? "" : dr["alarmtype"]), Convert.ToInt32(dr["id"] == DBNull.Value ? 0 : dr["id"]), dtStr);
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("查询数据异常" + e.Message);
            }
        }
        public static void GetInfox(int day = 0)
        {
            try
            {
                string dtStr = DateTime.Now.AddDays(day).ToString("yyyyMMdd");
                if (DateTime.Now.Hour < 7)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_FileResourceInfo{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sqlCt = $@"create table IF NOT EXISTS qskjrecord.B_FileResourceInfo{dtStr}
                                (
                                   id                   bigint not null auto_increment,
                                   typeinfo             bigint comment '类型信息，1-稽查，2-录像下载，3-报警',
                                   alarmId              varchar(300) comment '报警Id',
                                   platform             varchar(50) comment '文件来源平台',
                                   filetype             varchar(50) comment '文件类型',
                                   filekey              varchar(50) comment '视图库key值',
                                   company              varchar(50) comment '公司',
                                   filiale              varchar(50) comment '车队',
                                   license              varchar(50) comment '车牌',
                                   driver               varchar(50) comment '驾驶员',
                                   ipaddress            varchar(50) comment 'IP地址',
                                   urladdress           text comment '文件地址',
                                   createtime           datetime comment '创建时间',
                                   updatetime           datetime comment '更新时间',
                                   pid                  bigint comment '关联表数据Id',
                                   primary key (id)
                                );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlCt);
                    }
                }
                string sql = $@"select a.* from qskjrecord.B_Vehicle_AlarmAndFile{dtStr} a
                                left join qskjrecord.B_FileResourceInfo{dtStr} b on a.id=b.pid
                                join qskj.R_Alarm_Type c on a.alarmtype=typeId
                                where (((a.platform='RUIMING' or a.platform='zl') and c.busOrCar='c')or (a.platform='ZAKJ' and c.busOrCar='b')) and c.threeClassId=1 and LENGTH(a.url)>0 and  b.id is null AND url NOT REGEXP '.no' and url NOT REGEXP '.bin'  order by a.id limit 1000;";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    string x = dr["url"].ToString().Replace("61.171.114.101", "192.168.3.231");
                    string[] strUrl = x.Split(';');
                    //Console.WriteLine(x);
                    foreach (string strUrl2 in strUrl)
                    {
                        if (string.IsNullOrWhiteSpace(strUrl2) || strUrl2.Contains(".no") || strUrl2.Contains(".bin"))
                        {
                            continue;
                        }
                        UploadFileVideo(strUrl2, dr["alarmId"].ToString(), dr["platform"].ToString(), Convert.ToString(dr["alarmtype"] == DBNull.Value ? 0 : dr["alarmtype"]), Convert.ToInt32(dr["id"] == DBNull.Value ? 0 : dr["id"]), dtStr);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("查询数据异常" + e.Message);
            }
        }
        public static void UploadFileVideo(string? videourl = "https://rvming.zx62580.com:48086/videoAlarm/2024/06/18/沪ADW7185/141342_2779046762_49.jpg", string? alarmId = "0", string? platfrom = "unkno", string alarmtype = "", int pid = 0, string? dtStr = "")
        {
            try
            {
                List<AlarmType> at = GetAlarmTypes();
                //int[] bus = { 1, 2, 3, 5, 6, 15, 16, 17, 39, 43 };
                //int[] car = { 1, 2, 17, 30, 31, 32, 33, 34, 35, 44, 87, 88, 89, 90, 91, 92, 93, 113, 122 };
                List<string> bus = at.Where(p => p.busOrCar == "b" && p.thresClassId == "1").Select(p => p.typeId).ToList();
                List<string> car = at.Where(p => p.busOrCar == "c" && p.thresClassId == "1").Select(p => p.typeId).ToList();
                if (platfrom == "RUIMING" || platfrom == "zl")
                {
                    //出租平台
                    if (!car.ToList().Exists(p => p == alarmtype))
                    {
                        return;
                    }
                }
                else
                {
                    //大巴平台
                    if (!bus.ToList().Exists(p => p == alarmtype))
                    {
                        return;
                    }
                }
                string[] filetype = videourl.Split('.');
                string[] filename = videourl.Split('/');
                string filetype1 = filetype[(filetype.Length - 1)];
                string filename1 = filename[(filename.Length - 1)];
                string bt = DateTime.Now.ToString("yyyyMMddHHmmss"), urladdress = string.Empty;
                string strKey = bt + DateTime.Now.Ticks, fileName = "videoFile_" + filename1;
                string localFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName;
                // 创建目标文件夹（如果不存在）
                Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
                if (!File.Exists(localFilePath))
                {
                    // 下载文件并保存到本地
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(videourl, localFilePath);
                    }
                    if (filetype1 == "mp4")
                    {
                        try
                        {
                            //string? videourl = "https://rvming.zx62580.com:48086/videoAlarm/2024/06/17/沪AC15032/02_03_0_0_253418146.mp4";
                            #region 上传文件信息
                            var dataInfoRes = PostFileDataInfo(strKey, "mp4", fileName, bt); Thread.Sleep(10);
                            DataInfo responseDataInfo = new DataInfo();
                            responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                            #endregion
                            #region 上传文件 
                            {
                                try
                                {
                                    var dataRes = PostFileData(strKey, localFilePath);
                                    DataFile responseData = new DataFile();
                                    responseData = JsonConvert.DeserializeObject<DataFile>(dataRes.Result);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("上传文件异常" + e.ToString());
                                }
                            }
                            #endregion
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("上传文件信息异常" + e.ToString());
                        }
                    }
                    else
                    {
                        try
                        {
                            //string? videourl = "https://rvming.zx62580.com:48086/videoAlarm/2024/06/18/沪ADW7185/141342_2779046762_49.jpg"
                            string strBase64 = string.Empty;
                            // 读取图片文件到字节数组
                            byte[] imageBytes = File.ReadAllBytes(localFilePath);
                            using (var memoryStream = new MemoryStream(imageBytes))
                            {
                                // 将字节数组转换为MemoryStream 
                                strBase64 = Convert.ToBase64String(memoryStream.ToArray());
                            }

                            #region 上传文件信息&上传文件 
                            var dataInfoRes = PostImageFileData(strKey, filetype1, fileName, strBase64);
                            DataInfo responseDataInfo = new DataInfo();
                            responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                            urladdress = responseDataInfo?.ResponseStatusListObject?.ResponseStatusObject[0]?.ImageInfo?.StoragePath;
                            #endregion
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("上传文件信息&上传文件异常" + e.ToString());
                        }
                    }
                    #region 记录上传信息
                    {
                        //删除本地资源文件
                        File.Delete(localFilePath);
                        string sql = $@"insert into qskjrecord.B_FileResourceInfo{dtStr}(typeinfo,alarmId,platform,filetype,filekey,createtime,pid,begintime,urladdress)values(3,'{alarmId}','{platfrom}','{filetype1}','{strKey}',now(),{pid},'{bt}','{urladdress}')";
                        if (string.IsNullOrWhiteSpace(urladdress))
                        {
                            sql = $@"insert into qskjrecord.B_FileResourceInfo{dtStr}(typeinfo,alarmId,platform,filetype,filekey,createtime,pid,begintime,urladdress)values(3,'{alarmId}','{platfrom}','{filetype1}','{strKey}',now(),{pid},'{bt}',null)";
                        }
                        else
                        {
                            string[] ips = urladdress.Split(':'); string ip = ips[1].Replace("/", "");
                            sql = $@"insert into qskjrecord.B_FileResourceInfo{dtStr}(typeinfo,alarmId,platform,filetype,filekey,createtime,pid,begintime,urladdress,ipaddress,updatetime)values(3,'{alarmId}','{platfrom}','{filetype1}','{strKey}',now(),{pid},'{bt}','{urladdress}','{ip}',now())";
                        }
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(videourl);
                Console.WriteLine("文件处理异常" + e.ToString());
            }
        }
        public static List<AlarmType> GetAlarmTypes()
        {
            if (cSRedisClient == null)
            {
                cSRedisClient = RedisHelp.GetInstance();
            }
            List<AlarmType> alarmTypes = new List<AlarmType>();
            string alarmType = cSRedisClient.Get("alarmType");
            if (string.IsNullOrWhiteSpace(alarmType))
            {
                string sql = "select typeId,typeName,busOrCar,qskjId,qskjName,threeClassId from qskj.R_Alarm_Type";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    AlarmType a = new AlarmType();
                    a.typeId = dr["typeId"] == DBNull.Value ? "" : dr["typeId"].ToString();
                    a.typeName = dr["typeName"] == DBNull.Value ? "" : dr["typeName"].ToString();
                    a.busOrCar = dr["busOrCar"] == DBNull.Value ? "" : dr["busOrCar"].ToString();
                    a.qskjId = dr["qskjId"] == DBNull.Value ? "" : dr["qskjId"].ToString();
                    a.qskjName = dr["qskjName"] == DBNull.Value ? "" : dr["qskjName"].ToString();
                    a.thresClassId = dr["threeClassId"] == DBNull.Value ? "" : dr["threeClassId"].ToString();
                    alarmTypes.Add(a);
                }
                cSRedisClient.Set("alarmType", JsonConvert.SerializeObject(alarmTypes), new TimeSpan(23, 59, 59));
            }
            else
            {
                alarmTypes = JsonConvert.DeserializeObject<List<AlarmType>>(alarmType);
            }
            return alarmTypes;
        }
    }
    public class AlarmType
    {
        public string? typeId { get; set; }
        public string? typeName { get; set; }
        public string? busOrCar { get; set; }
        public string? qskjId { get; set; }
        public string? qskjName { get; set; }
        public string? thresClassId { get; set; }
    }
}
